package com.java.serverpackage;
import java.util.ArrayList;

public class ClientRoom {
	protected ArrayList<ClientRunnable> clients;
	protected ArrayList<MessagePacket> history;
	protected int roomId;
	protected int members = 0;
	
	public ClientRoom() {
		clients = new ArrayList<ClientRunnable>();
		history = new ArrayList<MessagePacket>();
	}
	
	public ClientRoom(int roomId) {
		clients = new ArrayList<ClientRunnable>();
		history = new ArrayList<MessagePacket>();
		this.roomId = roomId;
	}
	
	public void addClient(ClientRunnable client) {
		clients.add(client);
		members++;
	}
	
	public int getId(){
		return this.roomId;
	}
	
	public int getMembers() {
		return members;
	}
	
	public boolean isEmpty() {
		if(members == 0) {
			return true;
		}
		return false;
	}
	
	public void addHistory(MessagePacket msg) {
		history.add(msg);
	}
	
	// If a client disconnects, call removeClient to remove it from the room
	// this will allow newly connected clients to join an existing room and help
	// MultiThreadedServer to avoid creating more rooms than necessary
	public void removeClient(ClientRunnable client) {
		clients.remove(client);
		members--;
	}
	
	public ArrayList<ClientRunnable> getClientList() {
		return this.clients;
	}
	
	public ArrayList<MessagePacket> getHistory() {
		return this.history;
	}
	
	public void broadcast(MessagePacket msg, ClientRunnable currentClient) {
		synchronized(this) {
			if(msg != null) {
				for(ClientRunnable client : clients) {
					if(client.equals(currentClient))
						continue;
					try {
						client.getOutputStream().writeObject(msg); // Get the ClientRunnables ObjectOutputStream
					} catch (Exception e) {
						System.out.println("Crash in the broadcast function");
					}
				}
			}
		}
	}
	
}
